import axios, { type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
import { getToken } from './auth'
import { ResultEnum } from '../enums/ResultEnum'
import { ElMessage } from 'element-plus'

const service = axios.create({
	baseURL: import.meta.env.VITE_APP_BASE_API,
	timeout: 5000,
	headers: { 'Content-Type': 'application/json;charset=utf-8' },
})

// 请求拦截器
service.interceptors.request.use(
	(config: InternalAxiosRequestConfig) => {
		const accessToken = getToken()
		// 如果 Authorization 设置为 no-auth，则不携带 Token，用于登录、刷新 Token 等接口
		if (config.headers.Authorization !== 'no-auth' && accessToken) {
			config.headers.Authorization = accessToken
		} else {
			delete config.headers.Authorization
		}
		return config
	},
	(error) => Promise.reject(error)
)

// 响应拦截器
service.interceptors.response.use(
	(response: AxiosResponse) => {
		// 如果响应是二进制流，则直接返回，用于下载文件、Excel 导出等
		if (response.config.responseType === 'blob') {
			return response
		}
		const { code, data, msg } = response.data
		if (code === ResultEnum.SUCCESS) {
			return data
		}
		ElMessage.error(msg || '系统出错')
		return Promise.reject(new Error(msg || 'Error'))
	},
	async (error: any) => {
		if (error.response.data) {
			const { code, msg } = error.response.data
			// token 过期，跳转登录页
			if (code === ResultEnum.ACCESS_TOKEN_INVALID) {
				ElMessage.error(msg)
				setTimeout(() => {
					localStorage.clear()
					window.location.href = '/'
				}, 2000)
			} else {
				ElMessage.error(msg || '系统出错')
			}
		}
		return Promise.reject(error.message)
	}
)

export default service
